package myJs.admin.changeEmail

import myJs.api.Api
import myJs.myPkg.yup._

import scala.collection.mutable
import scala.concurrent.Future
import scala.scalajs.js
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import shared.pojo.Pojo.{EmailData, Login, PhoneData, UserNameData}

import scala.scalajs.js.JSConverters._

/**
 * Created by yz on 7/12/2022
 */
object Schema {

  case class ValidInfo(v: String, valid: Boolean)

  val cacheMap = mutable.SeqMap[String, ValidInfo]()

  def cacheTest(key: String)(f: String => Future[Boolean]) = (v: String) => {
    val beforeV = cacheMap.getOrElse(key, ValidInfo("", true))
    if (beforeV.v != v) {
      f(v).map { x =>
        cacheMap.put(key, ValidInfo(v, x))
        x
      }.toJSPromise
    } else {
      Future {
        beforeV.valid
      }.toJSPromise
    }
  }

  def nameValidateF(key: String) = cacheTest(key) { v: String =>
    val request = UserNameData(name = v)
    Api.userNameCheck(request).map { response =>
      response.valid
    }
  }

  def emailValidateF(key: String) = cacheTest(key) { v: String =>
    val request = EmailData(email = v)
    Api.emailCheck(request).map { response =>
      response.valid
    }
  }

  def phoneValidateF(key: String) = cacheTest(key) { v: String =>
    val request = PhoneData(phone = v)
    Api.phoneCheck(request).map { response =>
      response.valid
    }
  }


  val schema = Yup.`object`().shape(js.Dictionary(
    "password" -> Yup.string().required("密码不能为空！"),
    "email" -> Yup.string().required("新邮箱不能为空！")
//      .email("新邮箱不合法！"),
  ))
}
